﻿using CaseManagerLibrary.Auth;
using CaseManagerLibrary.Models;
using ScannerWatcher.Service;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ScannerWatcher
{
    public partial class FrmMain : Form
    {
        private Action<string> showMain;
        UserLogin login = new UserLogin();
        FrmCaseTree caseTree = new FrmCaseTree();

        public FrmMain()
        {
            InitializeComponent();

            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;



            this.Controls.Add(login);
            login.SetTitle(Properties.Resources.title_scanwatcher);
            login.Size = this.ClientSize;
            login.BringToFront();
            login.LoginSuccess += Login_LoginSuccess;
            login.LoginFail += Login_LoginFail;

            caseTree.OnSelectCategory += CaseTree_OnSelectCategory;
            caseTree.OnUnSelectCategory += CaseTree_OnUnSelectCategory;


            this.lblUploadTip.Visible = false;
            this.progressBar1.Visible = false;

            showMain = new Action<string>(delegate (string filePath)
            {
                this.WindowState = FormWindowState.Normal;
                this.StartPosition = FormStartPosition.CenterScreen;
                this.ShowInTaskbar = true;
                this.Show();

                if (LoginService.User == null)
                {
                    login.Show(filePath);
                }
                else
                {
                    login.Hide();
                }

                AddFile(filePath);
            });
        }

        private void ShowUserLogin(UserLogin login, object data)
        {
            login.Show(data.ToString());
        }

        private void CaseTree_OnUnSelectCategory(Models.case_question_category category, FileItem fileItem)
        {
            fileItem.RefreshCategory();
        }

        private void CaseTree_OnSelectCategory(Models.case_question_category category, FileItem fileItem)
        {
            if (category != null)
            {
                fileItem.ParentNode = category;
            }
        }

        private void Login_LoginFail(string msg)
        {
            MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void Login_LoginSuccess(ac_user user, object data)
        {
            login.Hide();

            CaseHelper.LoadCaseInfo(LoginService.User.id);

            for (int i = 0; i < palFileList.Controls.Count; i++)
            {
                (palFileList.Controls[i] as FileItem).SetCaseList(CaseHelper.CaseList);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        public void ShowMain(string filePath)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(showMain, filePath);
            }
            else
            {
                showMain(filePath);
            }
        }

        private void AddFile(string filePath)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                FileItem item = new FileItem();
                item.OnUndefinedClick += Item_OnUndefinedClick;
                item.OnCategoryClick += Item_OnCategoryClick;
                palFileList.Controls.Add(item);
                item.Dock = DockStyle.Top;
                item.BringToFront();

                string file_name = System.IO.Path.GetFileName(filePath);
                string file_ext = System.IO.Path.GetExtension(filePath);

                item.No = palFileList.Controls.Count;
                item.FileName = file_name.Replace(file_ext, "");
                item.FilePath = filePath;
                if (file_ext.ToLower().Contains("doc"))
                {
                    item.FileType = "word";
                }
                else if (file_ext.ToLower().Contains("pdf"))
                {
                    item.FileType = "pdf";
                }
                else
                {
                    item.FileType = "file";
                }

                this.lblFileCount.Text = "已扫描 " + palFileList.Controls.Count.ToString() + " 个文件";

                this.palFileList.BackgroundImage = null;
            }
        }

        private void Item_OnCategoryClick(object sender, EventArgs e)
        {
            var ci = (sender as FileItem).CaseInfo;
            if (ci != null)
            {
                caseTree.StartPosition = FormStartPosition.CenterScreen;
                caseTree.Show();
                caseTree.FileItem = (sender as FileItem);
                caseTree.LoadCategory(ci.id);
            }
        }

        private void Item_OnUndefinedClick(object sender, EventArgs e)
        {

        }

        private void palFileList_SizeChanged(object sender, EventArgs e)
        {
            login.Size = this.ClientSize;
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            this.progressBar1.Minimum = 0;
            this.progressBar1.Maximum = palFileList.Controls.Count;
            this.progressBar1.Value = 0;

            this.lblUploadTip.Visible = true;
            this.progressBar1.Visible = true;

            for (int i = palFileList.Controls.Count - 1; i >= 0; i--)
            {
                var item = (FileItem)palFileList.Controls[i];

                if (item.Save().success)
                {
                    System.IO.File.Delete(item.FilePath);

                    palFileList.Controls.RemoveAt(i);

                    this.progressBar1.Value += 1;

                    this.Refresh();

                    Application.DoEvents();
                }
            }

            this.lblFileCount.Text = "已扫描 " + palFileList.Controls.Count.ToString() + " 个文件";

            this.lblUploadTip.Visible = false;
            this.progressBar1.Visible = false;

            string msg = "";
            if (palFileList.Controls.Count == 0)
            {
                msg = "文件已全部上传成功！";
            }
            else
            {
                msg = "上传成功" + this.progressBar1.Value.ToString() + "个文件，上传失败" + (this.progressBar1.Maximum - this.progressBar1.Value).ToString() + "个文件";
            }

            MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnCaseSync_Click(object sender, EventArgs e)
        {
            CaseHelper.LoadCaseInfo(LoginService.User.id);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            login.Logout();
            e.Cancel = true;
        }
    }
}
